const express = require("express");
const router = express.Router();
const { Course } = require("../../models");
const { success, failure } = require("../../utils/responses");
const { paging } = require("../../utils/utils");
const { Op } = require("sequelize");

/**
 * 搜索课程列表
 * GTE  /search
 */
router.get("/", async function (req, res, next) {
  // 查询所有数据
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      attributes: { exclude: ["CategoryId", "UserId", "content"] },
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };

    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }

    // 分页查询
    const { count, rows } = await Course.findAndCountAll(condition);
    // 返回
    success(res, "课程搜索成功", {
      Courses: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
